package com.ibeetl.bbs;

import com.ibeetl.bbs.dao.BbsPostDao;
import com.ibeetl.bbs.dao.BbsTopicDao;
import com.ibeetl.bbs.model.BbsPost;
import com.ibeetl.bbs.model.BbsTopic;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.TimerTask;
@Service
@Slf4j
public class SpiderJobDetail extends TimerTask {

    @Autowired
    private BbsTopicDao topicDao;
    @Autowired
    private BbsPostDao postDao;
    int sourceId  = -1 ;
    @Override
    public void run() {
        Random random = new Random();
        try {
            if(sourceId==-1) {
                sourceId = topicDao.getMaxSourceId();
            }

            sourceId++;

            Source source = parse(sourceId);


            BbsTopic bbsTopic = new BbsTopic();


            bbsTopic.setSourceId(sourceId);
            bbsTopic.setContent(source.getTitle());
            bbsTopic.setUserId(95);
            bbsTopic.setPostCount(random.nextInt(100000));
            bbsTopic.setPv(random.nextInt(100000));
            bbsTopic.setReplyCount(random.nextInt(100000));
            bbsTopic.setModuleId(0);
            bbsTopic.setCreateTime(new Date());
            bbsTopic.setIsNice(0);
            bbsTopic.setIsUp(0);
            topicDao.insert(bbsTopic);
            int topicId = topicDao.getMaxTopicId();

            BbsPost bbsPost = new BbsPost();
            bbsPost.setContent(source.getContent());
            bbsPost.setTopicId(topicId);
            bbsPost.setCreateTime(new Date());
            bbsPost.setUserId(95);
            bbsPost.setHasReply(1);
            postDao.insert(bbsPost);
            log.info("success->{}",sourceId);
        }catch (Exception exception){
           log.error("exception->",exception);

        }

    }

    private Source parse(int sourceId) throws IOException {

        Document document = getHtml("https://www.auplanking.com/article/"+sourceId);

        String title = document.getElementsByTag("title").first().text();
        title = title.replaceAll("留澳规划帝","").replaceAll(" ","").replaceAll("-","");
        Element element = document.getElementsByAttributeValue("class", "detail").first();
        String str = element.toString();
        return new Source(title,str);
    }

    public  Document getHtml(String url) throws IOException {
        return  Jsoup.connect(url).timeout(Integer.MAX_VALUE).get();
    }

    @Data
    @AllArgsConstructor
    class Source{
        String title;
        String content;

    }
}
